# -*- coding: utf-8 -*-
# -*- frozen_string_literal: true -*-
require "lorca/manifest"
require "lorca/version"
require "sdbm"
require "csv"
require "digest/sha2"

module LorcaPrepRelease
  def self.package
    # Unless many tasks require cleaning stuff don't require "rake/clean"
    # More tasks make `rake -T` less readable.

    # system calls not unit-tested
    old_gem = Dir["#{gem_name}-*.gem"].first.to_s

    File.delete(old_gem) if File.exist? old_gem
    system "gem", "build", "#{gem_name}"
  end

  def self.import_wordlist txtfile, to:
    db_file = File.basename txtfile, ".txt"
    db_file = to + "/" + db_file

    SDBM.open(db_file) do |db|
      CSV.foreach(txtfile, col_sep: "\t") { |k, v| db[k] = v }
    end
  end

  def self.checksum gem, archive:
    filename = File.basename(gem) + ".sha512"
    checksum = Digest::SHA512.new.hexdigest(File.read(gem))

    File.open(File.join(archive, filename), "w") { |f| f.write checksum }
    checksum
  end

  def self.commit_checksum archive:
    fail "Must create checksum file before trying to do commit" unless checksum_in?(archive)

    # system calls not unit-tested
    nothing_staged = system "git", "diff", "--staged", "--exit-code", out: "/dev/null"
    fail "Can't commit checksum when there are staged elements" unless nothing_staged

    system "git", "add", checksum_file_under(archive)
    system "git", "commit", %Q[--message="Add checksum for version #{version}"]
  end

  def self.tag_release_commit archive:
    fail "Must add checksum before tagging a release" unless checksum_in?(archive)

    # system calls not unit-tested
    system "git", "tag", "--annotate", "v#{version}",
      %Q[--message="Release #{version}"]
  end

  def self.publish_gem
    # system calls not unit-tested
    system "git", "push", "--follow-tags"
    system "gem", "push", "#{built_gem}"
  end

  private

  def self.checksum_in? archive
    File.exist? checksum_file_under(archive)
  end

  def self.checksum_file_under archive
    "#{archive}/#{built_gem}.sha512"
  end

  def self.built_gem
    "#{gem_name}-#{version}.gem"
  end

  def self.gem_name
    Lorca::LorcaManifest.gem_name
  end

  def self.version
    Lorca::LorcaVersion
  end
end
